using System;
using System.Collections.Generic;
using System.IO;

using AvantGameMachine.DataManagement;
using System.ComponentModel;
using System.Threading;

namespace AvantGameMachine.FileSystem
{
	public class FileInformation : FileEntry
	{
		private FileInfo FInfo;
		private bool isLoaded = false;
		private object data = null;
        private long bRead = 0;

		internal FileInformation(FileInfo _info):base(false)
		{
			this.FInfo = _info;
		}
		
		internal bool IsLoaded {
			get { return isLoaded; }
		}

		internal FileInfo Info {
			get { return FInfo; }
		}
		
		internal object GetData() {
			if (data == null)
				LoadFile();
			return data;
		}

        internal byte[] GetBytes()
        {
            return (byte[])GetData();
        }

        internal bool LoadFile()
        {
            long temp;
            return LoadFile(out temp,false);
        }

        internal long AlreadyRead
        {
            get { return bRead; }
        }

		internal bool LoadFile(out long _read,bool _mt)
        {
            long blockRead = 2048;
            bRead = 0;
            _read = 0;

			if (!isLoaded)
            {
				FileStream reader = null;
				try
                {
					reader = FInfo.OpenRead();
                    long length = reader.Length;
					byte[] bData = new byte[length];
                    bool exit = false;
                    while (bRead < length && !exit)
                    {
                        blockRead = (length - bRead) >= blockRead ? blockRead : length - bRead;
                        if (_mt)
                        {
                            Thread.Sleep(1);
                        }

                        int currRead = reader.Read(bData, (int)bRead, (int)blockRead);
                        lock (this)
                        {
                            bRead += currRead;
                            _read = bRead;
                        }

                        if (currRead < blockRead)
                            exit = true;
                    }
					data = bData;
                    _read = (long)bRead;
					isLoaded = true;
					reader.Close();
				} catch (Exception)
                {
					if (reader != null)
						reader.Close();
                    _read = 0;
					return false;
				}
				return true;
			}
            _read = 0;
			return true;
		}
	}
}

